extends Control

# Nodes
@export var is_auto:bool = false
@onready var progress: ProgressBar = find_child("Progress")
@onready var loading: AnimatedSprite2D = find_child("Loading")
@onready var next: Button = find_child("Next")
@onready var label: Label = find_child("Label")
var count:int = 0
var is_updating:bool = false
var interval:float = 1

var gap = 30

func _ready():
	GameSceneSystem.load_percent_changed.connect(percent_changed)
	GameSceneSystem.load_finished.connect(loading_finished)
	GameSceneSystem.load_scene_interactive(GameSceneSystem.get_recorded_scene_id())

func percent_changed(number: int) -> void:
	progress.value = max(number - gap, 0)
	if progress.value >= 90:
		label.text = "World Generation . . ."

func loading_finished() -> void:
	if progress.value == 100:
		if is_auto:
			_on_next_button_up()
			return
		loading.visible = false
		next.visible = true
		label.text = ""
	elif progress.value == 70:
		GameSceneSystem.add_loaded_scene_to_scene_tree()
		gap = 0
		label.text = "Scene Initialization . . ."
		if not is_updating:
			_update_progress()

func _on_next_button_up():
	var fade_out_options = GameSceneSystem.create_options(1.0, "scribbles", 0.2, true)
	var fade_in_options = GameSceneSystem.create_options(1.0, "crooked_tiles", 0.2, true)
	var general_options = GameSceneSystem.create_general_options(Color(0, 0, 0), 0, false, true)
	GameSceneSystem.change_scene_to_existing_scene_in_scene_tree(fade_out_options, fade_in_options, general_options)
func _update_progress():
	is_updating = true
	await get_tree().create_timer(interval).timeout
	count += 1
	if count == 1:
		GameSceneSystem.load_percent_changed.emit(80 + randi_range(0, 9))
	elif count == 2:
		GameSceneSystem.load_percent_changed.emit(90 + randi_range(0, 9))
	elif count == 3:
		GameSceneSystem.load_percent_changed.emit(100)
		GameSceneSystem.load_finished.emit()
		count = 0
		is_updating = false
		return
	_update_progress()
